import { defineStore } from 'pinia'
import { login } from '@/api/auth'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}')
  }),

  actions: {
    async login(credentials) {
      try {
        const response = await login(credentials)
        if (response.data?.token) {
          this.token = response.data.token
          localStorage.setItem('token', response.data.token)
          if (response.data.userInfo) {
            this.userInfo = response.data.userInfo
            localStorage.setItem('userInfo', JSON.stringify(response.data.userInfo))
          }
          return true
        }
        return false
      } catch (error) {
        console.error('登录失败:', error)
        return false
      }
    },

    logout() {
      this.token = ''
      this.userInfo = {}
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    }
  }
})